var express = require('express');
var router = express.Router();
var db = require('../config/mysql');
var vertoken = require('../config/token');

function filterMenu(data) {
  let parents = data.filter(item => item.parentId == 0);
  let childs = data.filter(item => item.parentId != 0);
  childs.forEach(c => {
    parents.forEach(p => {
      c.parentId == p.id && (p.children ? p.children.push(c) : p.children = [c]);
    })
  });
  return parents
}

// 登录
router.post('/login', (req, res) => {
  let { userName, userPassword } = req.body;
  let sql = 'SELECT * FROM user WHERE username = ? AND userpassword = ?'
  if (userName === '' || !userPassword === '') {
    res.json({
      status: 500,
      message: '用户名或密码不能为空',
      data: null,
      timestamp: db.getTime()
    })
  } else {
    db.query(sql, [userName, userPassword], (reslute) => {
      if (!reslute.length) {
        res.json({
          status: 300,
          message: '登录账号或密码错误',
          data: null,
          timestamp: db.getTime()
        })
        return false;
      }
      // 登陆成功返回token
      vertoken.setToken(reslute[0].id, reslute[0].userRole, userName).then(token => {
        res.json({
          status: 200,
          message: '成功',
          data: {
            token,
            userName
          },
          timestamp: db.getTime()
        })
      })
    })
  }
})

// 根据登录用户权限获取路由列表
router.post('/getMenuTree', (req, res) => {
  // let sql = `SELECT m.* FROM menu m RIGHT JOIN rolemenu r ON r.roleId = ? AND r.menuId = m.id`;
  let sql = `SELECT m.* FROM menu m RIGHT JOIN rolemenu r ON r.roleId = ? AND r.menuId = m.id AND r.disable != 0 ORDER BY id`;
  db.query(sql, [req.data.userRole], (reslute) => {
    let data = filterMenu(reslute);
    res.json({
      status: 200,
      message: '成功',
      data,
      timestamp: db.getTime()
    })
  })
})

// 获取用户列表
router.post('/getUserList', async (req, res) => {
  let { userName, pageNo, pageSize } = req.body;
  let sql = `SELECT COUNT(id) AS total FROM user WHERE userName LIKE ?`;
  let sql2 = `SELECT u.id, u.userName, u.userRole, r.roleName FROM user u LEFT JOIN role r ON u.userRole = r.id WHERE userName LIKE ? limit ?,?`;
  // let sql2 = `SELECT id, userName, userRole FROM user WHERE userName LIKE ? limit ?,?`;
  let totalSql = await db.query(sql, [`%${userName || '%'}%`]);
  let reslute = await db.query(sql2, [`%${userName || '%'}%`, (pageNo - 1) * pageSize, pageSize]);
  res.json({
    status: 200,
    message: '成功',
    data: {
      total: totalSql[0].total,
      reslute
    },
    timestamp: db.getTime()
  })
})

// 新增用户
router.post('/addUser', (req, res) => {
  let { userName, userRole } = req.body;
  let sql = `SELECT * FROM user WHERE userName = ?`;
  db.query(sql, [userName], (reslute) => {
    if(!reslute.length) {
      let sql = `INSERT INTO user (userName, userRole) VALUES (?, ?)`;
      db.query(sql, [userName, userRole], (reslute) => {
        res.json({
          status: 200,
          message: '成功',
          data: reslute,
          timestamp: db.getTime()
        })
      })
    } else res.json({
      status: 300,
      message: '用户名重复',
      data: null,
      timestamp: db.getTime()
    })
  })
})

// 更新用户
router.post('/editUser', (req, res) => {
  let { userName, userRole, id } = req.body;
  let sql = `SELECT * FROM user WHERE userName = ? AND id != ?`;
  db.query(sql, [userName, id], (reslute) => {
    if(!reslute.length) {
      let sql = `UPDATE user SET userName = ?, userRole = ? WHERE id = ?`;
      db.query(sql, [userName, userRole, id], (reslute) => {
        res.json({
          status: 200,
          message: '成功',
          data: reslute,
          timestamp: db.getTime()
        })
      })
    } else res.json({
      status: 300,
      message: '用户名重复',
      data: null,
      timestamp: db.getTime()
    })
  })
})

// 删除用户
router.post('/delUser', (req, res) => {
  let { id } = req.body;
  let sql = `DELETE FROM user WHERE id = ?`;
  db.query(sql, [id], (reslute) => {
    res.json({
      status: 200,
      message: '成功',
      data: reslute,
      timestamp: db.getTime()
    })
  })
})

// 获取选中菜单下按钮权限
router.post('/getMenuButtons', (req, res) => {
  let { menuId } = req.body;
  let sql = `SELECT * FROM rolebtn WHERE menuId = ? AND roleId = ? AND disable = 1`;
  db.query(sql, [menuId, req.data.userRole], (reslute) => {
    res.json({
      status: 200,
      message: '成功',
      data: reslute,
      timestamp: db.getTime()
    })
  })
})

// 获取所有角色-无分页
router.post('/getRoleList', (req, res) => {
  let sql = `SELECT * FROM role`;
  db.query(sql, [], (reslute) => {
    res.json({
      status: 200,
      message: '成功',
      data: reslute,
      timestamp: db.getTime()
    })
  })
})

module.exports = router;